#!/bin/sh
#
#   http://code.google.com/media-translate/
#   Copyright (C) 2010  Serge A. Timchenko
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#

#
# Translate CGI module
# 'vimeo.com' plug-in
#
# version: 1.1 22.09.2010 0:57:50
#
# http://vimeo.com/13768695
# http://vimeo.com/moogaloop.swf?clip_id=13199616
#
# options:
#   HD:[0|1]

local TIMELIFE=60

stream_type=''
stream_url=''
server_type='vimeo'
protocol='http'

if echo "${arg_url}" | grep -q -s '\(www\.\)*vimeo\.com.*/\(moogaloop.swf?clip_id=\)*[0-9][0-9]*$'; then 

  local hdc=
  
  get_opt "HD"
  [ -z "$opt" ] && opt=$VIMEO_HD
  case $opt in
    yes|Yes|YES|1)
      hdc=$opt
    ;;
    *)
      hdc=''
  esac
  
  local video_id=`echo "$arg_url" | sed -e 's/.*\///;s/&.*//;s/.*=//'`
  
  local CACHEFILE=$CACHEPATH/vm.$video_id
  local tsttime=
  
  let tsttime=`date +%s`-$TIMELIFE
  
  local t_param=
  local hd_param=
  
  if [ -f $CACHEFILE ]; then
    if [ `date +%s -r $CACHEFILE` -gt $tsttime ]; then
      t_param=`sed -ne "1p" $CACHEFILE`
      hd_param=`sed -ne "2p" $CACHEFILE`
      icy_name=`sed -ne "3p" $CACHEFILE`
    fi
  fi
  
  if [ -z "$t_param" ]; then   
      host_response=`$MSDL -q -o ${TMPFILE} -p http --useragent "${USERAGENT}" http://vimeo.com/moogaloop/load/clip:$video_id 2>&1`
      if [ -f ${TMPFILE} ]; then
        local request_signature=`get_xml_text "request_signature"`
        local request_signature_expires=`get_xml_text "request_signature_expires"`
        icy_name=`get_xml_text "caption" | sed 's/&quot;/"/g'`
        hd_param=`get_xml_text "isHD"`
        
        t_param="${request_signature}/${request_signature_expires}"
  
        echo $t_param > $CACHEFILE
        echo $hd_param >> $CACHEFILE
        echo $icy_name >> $CACHEFILE
        rm -f $TMPFILE
      fi
  fi
  
  local suffix="?q=sd"
  
  if [ -n "$hdc" -a "$hd_param" = "1" ]; then
      suffix="?q=hd"
  fi
  
  if [ -n "$t_param" ]; then
    stream_url="http://vimeo.com/moogaloop/play/clip:${video_id}/${t_param}/${suffix}"
    buf=`test_stream 15 "-p http" "$stream_url"`
    stream_type=`echo "$buf" | sed -n '/^[Cc]ontent\-[Tt]ype:/p' | sed -n '$p' | /usr/local/etc/awk '{gsub(/\r/,""); print $2}' | sed 's/[,;]$//'`
    return $RC_OK
  fi
else
  check_av_stream
  return $RC_OK
fi

return $RC_FAIL
